package com.cloud.proxy.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * POST过滤器
 *
 * 从RequestContext中获取“serviceId”，也就是当前的服务名称，然后自定义一个HTTP头，并把服务名称添加到Response的HTTP头中
 *
 * @author qinxh
 * @date 2016/10/31
 */
@Component
public class PostFilter extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(PostFilter.class);

    /**
     * @return
     */
    @Override
    public String filterType() {

        // 设置为POST过滤器
        return FilterConstants.POST_TYPE;
    }

    /**
     * 设置过滤器的优先级
     *
     * @return
     */
    @Override
    public int filterOrder() {

        return 2;
    }

    @Override
    public boolean shouldFilter() {

        return Boolean.TRUE;
    }

    @Override
    public Object run() {

        RequestContext currentContext = RequestContext.getCurrentContext();

        Optional.ofNullable(currentContext.get("serviceId")).ifPresent( p -> {
            String serviceId = currentContext.get("serviceId").toString();
            logger.info("serviceId is {}", serviceId);
            currentContext.getResponse().setHeader("ServiceName", serviceId);
        });

        return null;
    }
}
